#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <QKeyEvent>
#include <QMouseEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->action_open, &QAction::triggered, this, &MainWindow::action_open_slot);

    connect(ui->action_save_as, &QAction::triggered, this, &MainWindow::action_save_as_slot);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::action_open_slot()
{
    //获取选择的文件的路径
    QString fileName = QFileDialog::getOpenFileName(this,QStringLiteral("文件对话框"),"./",QStringLiteral("*"));

    if (fileName.isEmpty()) {
        qInfo("open3");
        QMessageBox::warning(this, "警告", "请选择一个文件");
        return;
    }
    qDebug()<<fileName;
    QFile fileObj(fileName);
    fileObj.open(QIODevice::ReadOnly);
    QByteArray fileData =  fileObj.readAll();
    ui->textEdit->setText(QString(fileData));
    this->setWindowTitle(fileObj.fileName());
    fileObj.close();
}

void MainWindow::action_save_as_slot()
{
    qDebug()<<"save as";
    QString fileName = QFileDialog::getSaveFileName(this, "请选择一个文件", "./");
    if (fileName.isEmpty()) {
        return;
    }
    QFile fileObj(fileName);
    fileObj.open(QIODevice::WriteOnly);
    QByteArray ba;
    ba.append(ui->textEdit->toPlainText());
    fileObj.write(ba);
    fileObj.close();

}

void MainWindow::keyPressEvent(QKeyEvent *k)
{
    qDebug()<< "key press";
    if (k->modifiers() == Qt::ControlModifier && k->key() == Qt::Key::Key_S) {
        qDebug()<< "key ctrl + s press";
    }
}

void MainWindow::mousePressEvent(QMouseEvent *m)
{
    if (m->button() == Qt::MouseButton::LeftButton) {
        qDebug()<< m->pos();
    }

}
